package jp.idahopotato.activity;

import java.util.ArrayList;
import java.util.List;

import jp.idahopotato.adapter.SkillSetAdapter;
import jp.idahopotato.bean.Skill;
import jp.matome.activity.R;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class SkillSetActivity extends ListActivity {
	private static final String FILE_NAME = "PreferenceSkillSetFile";
	private static ListView lv = null;
	CreateProductHelper helper = null;
	SQLiteDatabase db = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO 自動生成されたメソッド・スタブ
		super.onCreate(savedInstanceState);
		setContentView(R.layout.skillset);
		final SharedPreferences pref = getSharedPreferences(FILE_NAME, MODE_PRIVATE);

		//前画面からの文字列を取得
		Intent data = getIntent();
		Bundle extras = data.getExtras();
		String str = extras.getString("SELECT_MENU");
		TextView title = (TextView)findViewById(R.id.text_skillset);
		title.setText(str);

		//スキルを追加する画面に遷移
		Button setBtn = (Button) findViewById(R.id.go_select_skill);
		setBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO 自動生成されたメソッド・スタブ
				Intent intent = new Intent(SkillSetActivity.this, SelectSkillActivity.class);
				intent.putExtra("SELECT_SKILL", "スキルセレクト");
				startActivityForResult(intent, 0);
			}
		});

		//設定したスキルを全消去
		Button clearBtn = (Button) findViewById(R.id.clear_skill);
		clearBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO 自動生成されたメソッド・スタブ
				((SkillSetAdapter)lv.getAdapter()).clear();
			}
		});

		//設定したスキル条件を確定して前画面に戻る
		Button backBtn = (Button)findViewById(R.id.backbutton_skillset);
		backBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				SharedPreferences.Editor editor = pref.edit();

				String selectedSet = "";
				SkillSetAdapter temp = (SkillSetAdapter) lv.getAdapter();
				for(int i=0; i<temp.getCount(); i++){
					Skill bean = temp.getItem(i);
					if(!selectedSet.equals("")){
						selectedSet += ",";
					}
					selectedSet += bean.getOnSkillId();
				}
				editor.putString("skillSet", selectedSet);
				editor.commit();
				Log.v("selected", selectedSet);

				Intent intent = getIntent();
				intent.putExtra("RETURN_FLAG", "スキル設定から");
				setResult(RESULT_OK, intent);

				finish();
			}
		});

		//設定してあったスキル条件の表示
		String skillSet = pref.getString("skillSet", "");
		helper = new CreateProductHelper(SkillSetActivity.this);
		String set[] = skillSet.split(",");
		try{
			//データベースを開く
			db = helper.getReadableDatabase();

			//各グループのスキル名の取得と、子リストの表示
			String columns[] = {"on_skill_id", "on_skill_name", "skill_description", "skill_point"};
			Cursor cursor;
			//アダプタ登録用全リスト
			List<Skill> list = new ArrayList<Skill>();
			SQLiteQueryBuilder build = new SQLiteQueryBuilder();
			build.setTables("t_on_skill LEFT JOIN m_skill ON(t_on_skill.skill_id = m_skill.skill_id)"
					+ "LEFT JOIN m_skill_group ON(m_skill.skill_group_id = m_skill_group.skill_group_id)");
			String where = "t_on_skill.on_skill_id = ?";
			for(int i=0; i<set.length; i++) {
				//検索条件は発動スキルID
				String[] param = {set[i]};
				String sql = build.buildQuery(columns, where, param, null, null, "on_skill_id ASC", null);
				cursor = db.rawQuery(sql, param);

				if(cursor.moveToFirst()){
					Skill skill = new Skill();
					skill.setOnSkillId(cursor.getString(0));
					skill.setOnSkillName(cursor.getString(1));
					skill.setDetail(cursor.getString(2));
					skill.setPoint(cursor.getString(3));
					list.add(skill);
				}
			}
			SkillSetAdapter adapter = new SkillSetAdapter(getApplicationContext(), list);
			setListAdapter(adapter);

		} catch(Exception e){
			Log.e("ERROR", e.toString());
		}
		db.close();
		lv = getListView();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data != null && data.hasExtra("RETURN_FLAG")){
			Bundle extras = data.getExtras();

			@SuppressWarnings({ "unchecked" })
			//スキル条件の追加
			ArrayAdapter<Skill> temp = (ArrayAdapter<Skill>)lv.getAdapter();
			Skill addSkill = new Skill();
			addSkill.setOnSkillId(extras.getString("ON_SKILL_ID"));
			addSkill.setOnSkillName(extras.getString("SKILL_NAME"));
			addSkill.setPoint(extras.getString("POINT"));
			addSkill.setDetail(extras.getString("DETAIL"));
			temp.insert(addSkill, 0);
		}
	}
}
